/**
 * Collaborative Story Development Web Application (CSDApp) Copyright Anton
 * Strack 2014
 *
 * This file is part of Collaborative Story Development Application (CSDApp).
 *
 * CSDApp is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or any later version.
 *
 * CSDApp is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * CSDApp. If not, see <http://www.gnu.org/licenses/>.
 *
 */
package csdwa;

import java.sql.Connection;

/**
 * The notification template controller handles the end user's interaction with
 * CRUD management of notification templates.
 *
 * @author Anton Strack
 */
public class NotificationController extends ResourceController {

    private final String VIEW_LIST = "/notification/index.jsp";
    private final String VIEW_VIEW = "/notification/view.jsp";
    private final String VIEW_CREATE = "/notification/create.jsp";
    private final String VIEW_UPDATE = "/notification/update.jsp";
    private final String VIEW_DELTE = "/notification/delete.jsp";

    public NotificationController(Connection conn) {
        super(conn);
    }

    /**
     * This method primarily handles form related requests.
     *
     * @param request the request object
     * @return an updated request object sufficient to complete the request.
     */
    @Override
    public CsdwaRequest handlePostRequest(CsdwaRequest request) {
        String form = request.getFormId();
        String primaryAction = request.getPrimaryActionTypeName();
        String primaryResource = request.getPrimaryResourceTypeName();
        int id = request.getPrimaryResourceId();
        if (form.isEmpty() == false) {
            if (form.equalsIgnoreCase("delete-notification")) {
                request.removeFormId();
                request = handleDelete(request);
            }
        } else // ajax
        {
            if (primaryAction.equalsIgnoreCase("delete") && id > 0) {
                request = handleDelete(request);
                request.setMessageType("success");
                request.setMessage("Success.");
            }
            request.setView("");
        }
        return request;
    }

    /**
     * This method handles get requests. It accepts the primaryResouce and
     * primaryAction as variables to allow routing from the handleGetRequest
     * method.
     *
     * @param request the request object
     * @return an updated request object sufficient to complete the request.
     */
    @Override
    public CsdwaRequest handleGetRequest(CsdwaRequest request) {
        String primaryAction = request.getPrimaryActionTypeName();
        String primaryResource = request.getPrimaryResourceTypeName();
        String secondaryResource = request.getSecondaryResourceTypeName();
        String secondaryAction = request.getSecondaryActionTypeName();
        int secondaryId = request.getSecondaryResourceId();
        int id = request.getPrimaryResourceId();
        if ("notification".equalsIgnoreCase(primaryResource)) {
            if ("view".equalsIgnoreCase(primaryAction) && id != 0) {
                NotificationTemplateDao ntDao = new NotificationTemplateDao(conn);
                NotificationDao nDao = new NotificationDao(conn);
                nDao.setUseRelatedMarkers(true);
                int result;
                result = nDao.selectBeanById(id);

                if (result > 0) {
                    Notification notification = nDao.getBean();
                    ntDao.setUseRelatedMarkers(true);
                    int result2 = ntDao.selectBeanById(notification.getNotificationTypeId());
                    if (result2 > 0) {
                        notification.setTemplate(ntDao.getBean());
                    }
                    request.setBean(notification);
                    request.setView(VIEW_VIEW);
                } else {
                    request.setMessage("The notification couldn't be found.");
                    request.setMessageType("error");
                    request.setPrimaryActionTypeName("list");
                    request.setPrimaryResourceTypeName("notification");
                    request.setPrimaryResourceId(0);
                    request = handleGetRequest(request);
                }

            } else if ("delete".equalsIgnoreCase(primaryAction) && secondaryResource != null) {
                // delete the notification and continue on to the notification subject.
                NotificationTemplateDao ntDao = new NotificationTemplateDao(conn);
                NotificationDao nDao = new NotificationDao(conn);
                int result;
                result = nDao.selectBeanById(id);
                if (result > 0) {
                    Notification notification = nDao.getBean();
                    request.setPrimaryActionTypeName("view");
                    request.setPrimaryResourceTypeName(secondaryResource);
                    request.setPrimaryResourceId(notification.getResourceId());
                    nDao.deleteBean(notification);
                    request = this.ResourceRequestDelegator.processRequest(request);
                }
            } else if ("delete".equalsIgnoreCase(primaryAction)) {
                Connection conn = this.conn;
                NotificationDao ndao = new NotificationDao(conn);
                int result = ndao.selectBeanById(id);
                if (result > 0) {
                    request = handleDelete(request);
                } else {
                    request.setMessage("The notification couldn't be found.");
                    request.setMessageType("error");
                    request.setPrimaryActionTypeName("list");
                    request.setPrimaryResourceTypeName("notification");
                    request.setPrimaryResourceId(0);
                    request = handleGetRequest(request);
                }
            } else {// index by default
                request.setView(VIEW_LIST);
                NotificationTemplateDao ntDao = new NotificationTemplateDao(conn);
                NotificationDao nDao = new NotificationDao(conn);

                nDao.setUseRelatedMarkers(true);
                int result;
                result = nDao.selectBeansByUserId(request.getCurrentUser().getId());
                if (result > 0) {
                    ntDao.clearDaoBeans();
                    ntDao.setUseRelatedMarkers(true);
                    int result2 = ntDao.selectBeanById(nDao.getBean().getNotificationTypeId());
                    if (result2 > 0) {
                        for (Notification notification : nDao.getBeans()) {
                            notification.setTemplate(ntDao.getBean());
                        }
                        request.setBeans(nDao.getBeans());
                    }
                } else {
                    request.setMessage("You have no notifications");
                    request.setMessageType("info");
                }
            }
        }
        return request;
    }

    /**
     * This method handles deleting the specific bean from the database.
     *
     * @param request the delete request object.
     * @return a request object with a requestResultMessage object specifying
     * the result.
     */
    private CsdwaRequest handleDelete(CsdwaRequest request) {
        // validate fields
        int id = request.getPrimaryResourceId();

        if (id > 0) {
            NotificationDao ndao = new NotificationDao(this.conn);
            Notification notification = new Notification();
            notification.setId(id);
            int result = ndao.deleteBean(notification);

            if (result > 0) {
                request.setMessage("The notification was successfully deleted from the site.");
                request.setMessageType("success");
                request.setPrimaryActionTypeName("list");
                request.setPrimaryResourceTypeName("notification");
                request.setPrimaryResourceId(0);
                request = handleGetRequest(request);
            } else {
                request.setMessage("There was an error trying to delete the notification from the database.");
                request.setMessageType("error");
                request.setPrimaryActionTypeName("view");
                request.setPrimaryResourceTypeName("notification");
                request.setPrimaryResourceId(id);
                request = handleGetRequest(request);
            }
        } else {
            request.setMessage("There was an error with the delete request. Could not determine the notification ID.");
            request.setMessageType("error");
            request.setPrimaryActionTypeName("list");
            request.setPrimaryResourceTypeName("notification");
            request.setPrimaryResourceId(0);
            request = handleGetRequest(request);
        }

        return request;
    }
}
